package com.arui.service.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.arui.constant.Constant;
import com.arui.dto.AruioUserDTO;
import com.arui.exception.ServiceException;
import com.arui.security.AruioUserDetail;
import com.arui.service.LoginService;
import com.arui.util.JwtUtil;
import com.arui.util.RedisCache;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Service;

/**
 * @Description 登录服务层
 * @Date 2024/8/27 9:19
 * @Created by 10574
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class LoginServiceImpl implements LoginService {
    private final AuthenticationManager authenticationManager;
    private final RedisCache redisCache;
    @Override
    public String login(AruioUserDTO aruioUserDTO) throws ServiceException {
        final String username = aruioUserDTO.getUsername();
        final String password = aruioUserDTO.getPassword();
        if (StringUtils.isBlank(username)) throw new ServiceException("用户名不能为空!");
        if (StringUtils.isBlank(password)) throw new ServiceException("密码不能为空!");
        final UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(username, password);
        Authentication authenticate = null;
        try {
            authenticate = authenticationManager.authenticate(authentication);
        } catch (AuthenticationException e) {
            throw new ServiceException(Constant.CODE_AUTH_ERROR, e.getMessage());
        }
        final AruioUserDetail aruioUserDetail = (AruioUserDetail) authenticate.getPrincipal();
        redisCache.setCacheObject(Constant.REDIS_LOGIN_PREFIX + aruioUserDetail.getAruioUser().getId(), aruioUserDetail);
        return JwtUtil.createJWT(String.valueOf(aruioUserDetail.getAruioUser().getId()));
    }
}
